package com.shengcheng.minio;

import io.minio.*;
import io.minio.errors.MinioException;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;


@Component
public class MinioUploader {
    @Autowired
    private MinioProperties minioProperties;


    @Autowired
    private MinioClient minioClient;

    @Bean
    @SneakyThrows
    public MinioClient minioClient(){
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpoint())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();

            // 创建一个桶
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("桶"+minioProperties.getBucketName()+"已经存在");
            }

            return minioClient;
    }

    public String uploaderFile(MultipartFile multipartFile) throws Exception{
        //设置存储对象名称
        String prefix = UUID.randomUUID().toString().replaceAll("-", " ");
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(originalFilename);
        String fileName = prefix+"."+suffix;

        minioClient.putObject(
                        PutObjectArgs.builder()
                            .bucket(minioProperties.getBucketName())
                            .object(fileName)
                            .stream(multipartFile.getInputStream(),multipartFile.getSize(),-1)
                            .contentType(multipartFile.getContentType())
                            .build());
            System.out.println("文件上传成功");


            String retUrl = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
            return retUrl;
    }
}